package main

// go get github.com/go-playground/validator/v10
import (
	"reflect"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
)

type User struct {
	ID   string `json:"id" binding: "required"`
	Name string `json:"name" binding:"required",min=3, max=7`
}
type RegisterForm struct {
	UserName string `json:"username" binding:"required,min=3,max=7"`
	Password string `json:"password" binding:"requied, len=8"`
	Age      uint32 `json:"age" binding:"required,gte=1, lte=150"`
	Email    string `json:"email" binding:"required,email"`
}

func main() {
	if err := InitializeTrans(); err != nil {

	}
	r := gin.Default()
	r.GET("user", func(c *gin.Context) {
		var user User
		// 绑定查询
		if err := c.ShouldBindJSON(&user); err != nil {
			err, ok := err.(validator.ValidationErrors)
			if !ok {
				c.JSON(200, gin.H{
					"code": 40010,
					"msg":  "注册失败",
					"err":  err.Error(),
				})
				return
			}

			c.JSON(200, gin.H{
				"code": 40040,
				"err":  err.Translate(trans),
			})
			return
		}

	})
	r.Run()
}

var trans ut.Translator

func InitializeTrans() (err error) {
	// Accept-Language
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterTagNameFunc(func(fld reflect.StructField) string {
			name := fld.Tag.Get("json")
			return name
		})
		zhT := zh.New()
		uni := ut.New(zhT, zhT)
		trans, _ = uni.GetTranslator("zh")
		err = zh_translations.RegisterDefaultTranslations(v, trans)
		return
	}
	return
}
